<template>
  <div>
    <el-button type="primary" @click="openMappingDialog">配置字段映射</el-button>

    <!-- 映射配置弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="字段映射配置"
      width="80%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div class="mapping-container">
        <div class="mapping-tools">
          <el-button type="primary" @click="addMapping">添加映射</el-button>
          <el-button 
            type="success" 
            @click="autoMapSameFields"
            :loading="isProcessing"
          >一键映射相同字段</el-button>
          <el-button 
            @click="clearMappings"
            :loading="isProcessing"
          >清空映射</el-button>
        </div>
        
        <!-- 使用el-scrollbar -->
        <el-scrollbar height="400px" class="mapping-list">
          <div 
            v-for="(item, index) in mappingsList" 
            :key="item.id" 
            class="mapping-item"
          >
            <div class="mapping-selects">
              <!-- 源字段选择 -->
              <div class="field-select" 
              :id="`source_select_${item.id}`">
                <el-input
                  v-if="!item.sourceFieldActive"
                  :model-value="getFieldLabel(item.sourceField)"
                  :placeholder="item.sourceField ? getFieldLabel(item.sourceField) : '选择源字段'"
                  readonly
                  @click="showSourceSelect(index)"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon"><ArrowDown /></el-icon>
                  </template>
                </el-input>
                <el-select
                  v-else
                  v-model="item.sourceField"
                  filterable
                  placeholder="选择源字段"
                  @blur="hideSourceSelect(index)"
                  popper-class="field-select-dropdown"
                >
                  <el-option
                    v-for="field in sourceFields"
                    :key="field.value"
                    :label="field.label"
                    :value="field.value"
                  />
                </el-select>
              </div>

              <el-icon class="mapping-arrow"><ArrowRight /></el-icon>

              <!-- 目标字段选择 -->
              <div class="field-select" 
              :id="`target_select_${item.id}`">
                <el-input
                  v-if="!item.targetFieldActive"
                  :model-value="getFieldLabel(item.targetField)"
                  :placeholder="item.targetField ? getFieldLabel(item.targetField) : '选择目标字段'"
                  readonly
                  @click="showTargetSelect(index)"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon"><ArrowDown /></el-icon>
                  </template>
                </el-input>
                <el-select
                  v-else
                  v-model="item.targetField"
                  filterable
                  placeholder="选择目标字段"
                  @blur="hideTargetSelect(index)"
                  popper-class="field-select-dropdown"
                >
                  <el-option
                    v-for="field in targetFields"
                    :key="field.value"
                    :label="field.label"
                    :value="field.value"
                  />
                </el-select>
              </div>
            </div>

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              circle
              @click="removeMapping(item.id)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </el-scrollbar>

        <!-- 映射统计信息 -->
        <div class="mapping-stats">
          <el-text class="mx-1" type="info">
            已映射: {{ mappingsMap.size }} / {{ sourceFields.length }} 个字段
          </el-text>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMappings">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { ArrowRight, Delete, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 模拟数据源字段
const sourceFields = ref([])
// 模拟目标字段
const targetFields = ref([])
// 处理状态
const isProcessing = ref(false)
// 映射数据
const mappingsMap = ref(new Map())
const dialogVisible = ref(false)

// 字段值到标签的映射缓存
const fieldLabelMap = ref(new Map())

// Select组件引用
const sourceSelectRefs = ref([])
const targetSelectRefs = ref([])

// 计算属性：映射列表
const mappingsList = computed(() => Array.from(mappingsMap.value.values()))

// 获取字段标签
const getFieldLabel = (fieldValue) => {
  if (!fieldValue) return ''
  return fieldLabelMap.value.get(fieldValue) || fieldValue
}

// 生成测试数据
const initTestData = () => {
  const testFields = Array.from({ length: 200 }, (_, i) => ({
    value: `field_${i}`,
    label: `字段${i}`
  }))
  
  sourceFields.value = testFields
  targetFields.value = testFields
  
  // 初始化字段标签映射
  fieldLabelMap.value.clear()
  testFields.forEach(field => {
    fieldLabelMap.value.set(field.value, field.label)
  })
}

// 显示/隐藏选择器
const showSourceSelect = (index) => {
  const item = mappingsList.value[index]
  item.sourceFieldActive = true
  nextTick(() => {
    setTimeout(() => {
      document.querySelector(`#source_select_${item.id} .el-select__wrapper`)?.click()
    }, 50)
  })
}

const hideSourceSelect = (index) => {
  const item = mappingsList.value[index]
  setTimeout(() => {
    item.sourceFieldActive = false
  }, 200)
}

const showTargetSelect = (index) => {
  const item = mappingsList.value[index]
  item.targetFieldActive = true
  nextTick(() => {
    setTimeout(() => {
      document.querySelector(`#target_select_${item.id} .el-select__wrapper`)?.click()
    }, 50)
  })
}

const hideTargetSelect = (index) => {
  const item = mappingsList.value[index]
  setTimeout(() => {
    item.targetFieldActive = false
  }, 200)
}

// 打开弹窗
const openMappingDialog = () => {
  // 确保数据已初始化
  if (sourceFields.value.length === 0) {
    initTestData()
  }
  dialogVisible.value = true
}

// 添加新映射
const addMapping = () => {
  const id = `mapping_${Date.now()}`
  mappingsMap.value.set(id, {
    id,
    sourceField: '',
    targetField: '',
    sourceFieldActive: false,
    targetFieldActive: false
  })
}

// 删除映射
const removeMapping = (id) => {
  mappingsMap.value.delete(id)
}

// 清空映射
const clearMappings = async () => {
  isProcessing.value = true
  try {
    mappingsMap.value.clear()
    ElMessage.success('已清空所有映射')
  } finally {
    isProcessing.value = false
  }
}

// 一键映射相同字段
const autoMapSameFields = () => {
  if (isProcessing.value) return
  
  isProcessing.value = true
  try {
    // 创建字段值到目标字段的映射表
    const targetFieldMap = new Map(
      targetFields.value.map(field => [field.value, field])
    )
    
    // 清空现有映射
    mappingsMap.value.clear()
    
    // 批量创建新的映射
    sourceFields.value.forEach(sourceField => {
      if (targetFieldMap.has(sourceField.value)) {
        const id = `mapping_${Date.now()}_${sourceField.value}`
        mappingsMap.value.set(id, {
          id,
          sourceField: sourceField.value,
          targetField: sourceField.value,
          sourceFieldActive: false,
          targetFieldActive: false
        })
      }
    })
    
    ElMessage.success(`已自动映射 ${mappingsMap.value.size} 个相同字段`)
  } catch (error) {
    console.error('映射处理失败:', error)
    ElMessage.error('映射处理失败，请重试')
  } finally {
    isProcessing.value = false
  }
}

// 保存映射配置
const saveMappings = () => {
  const mappingsArray = Array.from(mappingsMap.value.values())
  console.log('保存的映射配置:', mappingsArray)
  dialogVisible.value = false
  ElMessage.success('映射配置已保存')
}
</script>

<style scoped>
.mapping-container {
  padding: 20px;
}

.mapping-tools {
  margin-bottom: 20px;
}

.mapping-list {
  border: 1px solid #eee;
  border-radius: 4px;
}

.mapping-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  background: #fff;
}

.mapping-item:last-child {
  border-bottom: none;
}

.mapping-selects {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 20px;
}

.mapping-arrow {
  margin: 0 20px;
  color: #409EFF;
}

.field-select {
  width: 200px;
  position: relative;
}

/* 添加过渡效果 */
:deep(.el-select),
:deep(.el-input) {
  transition: all 0.2s ease-in-out;
  width: 100%;
}

.mapping-stats {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-input__wrapper) {
  cursor: pointer;
}

/* 确保下拉框样式正确 */
:global(.field-select-dropdown) {
  width: 200px !important;
}

:deep(.el-input__icon) {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  transition: transform 0.3s;
}

:deep(.el-input:hover .el-input__icon) {
  color: var(--el-text-color-regular);
}
</style> 